const querystring = require('querystring')
const handleBlogRouter = require("./src/router/blog")
const handleUserRouter = require('./src/router/user')

//处理postData
const getpostData = (req) => {
    const promise = new Promise((resolve, reject) => {
        // console.log(req)
        if (req.method !== "POST") {
            resolve({})
            return
        }
        // console.log(req.headers['content-type'])
        if (req.headers['content-type'] !== 'application/json') {
            resolve({})
            return
        }


        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            if (!postData) {
                resolve({})
                return
            }
            resolve(JSON.parse(postData))
        })
    })
    return promise;
}


const serverHandle = (req, res) => {
    //设置返回格式 JSON
    res.setHeader("Content-type", "application/json")

    // 解析query
    const url = req.url
    req.query = querystring.parse(url.split('?')[1])
    // console.log(req.query)


    //测试 解析cookie
    req.cookie={}
    const cookieStr=req.headers.cookie || ''
   
    cookieStr.split(';').forEach(item => {
        if(!item){
            return
        }
        const arr=item.split('=')
        
        const key=arr[0].trim()
        const val=arr[1].trim()
        req.cookie[key]=val
        console.log(key,val)
    });
    // console.log(req.cookie);


    //处理post data
    getpostData(req).then(postData => {
        req.body = postData
        // console.log(req.body)

        //处理blog路由
        // const blogData = handleBlogRouter(req, res)
        // if (blogData) {
        //     res.end(
        //         JSON.stringify(blogData)
        //     )
        //     return
        // }
        const blogResult = handleBlogRouter(req, res)
        if (blogResult) {
            blogResult.then(blogData => {
                res.end(
                    JSON.stringify(blogData)
                )
            })
            return
        }

        //处理user路由
        // const userData = handleUserRouter(req, res)
        // if (userData) {
        //     res.end(
        //         JSON.stringify(userData)
        //     )
        //     return
        // }

        const userResult = handleUserRouter(req, res)
        if (userResult) {
            userResult.then(userData => {
                res.end(
                    JSON.stringify(userData)
                )
            })
            return
        }

        //访问出错
        res.writeHeader(404, { "Content-type": "text/plain" })
        res.write("404 Not Fount")
        res.end()
    })



}

module.exports = serverHandle